﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using QMERP.Domain.Dtos;
using QMERP.Domain.Entities;
using QMERP.Domain.Enums;
using QMERP.Infrastructure.CustomException;
using QMERP.Infrastructure.EFCore;
using QMERP.Infrastructure.EFCore.Extensions;
using QMERP.Infrastructure.Extensions;
using QMERP.Infrastructure.Security;

namespace QMERP.Application.Services
{
    public class AppService : IAppService
    {
        private readonly IMapper _mapper;
        private readonly QMERPDbContext _db;
        private readonly ICurrentUser _currentUser;
        public AppService(IMapper mapper, QMERPDbContext db, ICurrentUser currentUser)
        {
            _mapper = mapper;
            _db = db;
            _currentUser = currentUser;
        }
        /// <summary>
        /// 获取应用列表基础数据
        /// </summary>
        /// <param name="types"></param>
        /// <returns></returns>
        public async Task<List<AppResponse>> GetBasicApps(params string[] types)
        {
            List<App> apps = await _db.App.GetBasicApps(types).ToListAsync();
            return _mapper.Map<List<AppResponse>>(apps);
        }
        /// <summary>
        /// 应用管理窗体
        /// </summary>
        /// <returns></returns>
        public async Task<List<AppResponse>> Query()
        {
            List<App> apps = await _db.App.ToListAsync();
            return _mapper.Map<List<AppResponse>>(apps);
        }
        /// <summary>
        /// 获取id的应用详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<AppResponse> Detail(long id)
        {
            var model = await _db.App.FindByIdAsync(id);
            return _mapper.Map<AppResponse>(model);
        }
        /// <summary>
        /// 应用保存
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="ApiException"></exception>
        public async Task Save(AppSaveRequest request)
        {
            if (request.Type != AppTypeEnum.Resource.ToString())
            {
                if (await _db.App.AnyAsync(x => x.Name!.ToLower() == request.Name && x.Id != request.Id && x.PId == request.PId))
                    throw new ApiException("路由名称已存在!");
                if (await _db.App.AnyAsync(x => x.Path!.ToLower() == request.Path && x.Id != request.Id && x.PId == request.PId))
                    throw new ApiException("路由路径已存在!");
            }
            App? model = _mapper.Map<App>(request);
            if (request.Id != null)
            {
                model = await _db.App.FindByIdAsync(request.Id.Value);
                if (model == null)
                    throw new ApiException("应用不存在!");
                model.PId = request.PId;
                model.Type = request.Type;
                model.Name = request.Name;
                model.Path = request.Path;
                model.Component = request.Component;
                model.Redirect = request.Redirect;
                model.License = request.License;
                model.Icon = request.Icon;
                model.Title = request.Title;
                model.IsHide = request.IsHide;
                model.IsKeepAlive = request.IsKeepAlive;
                model.IsAffix = request.IsAffix;
                model.IsIframe = request.IsIframe;
                model.IsLink = request.IsLink;
                model.Link = request.Link;
                model.Sort = request.Sort;
                model.Remark = request.Remark;
            }
            if (request.PId != null)
            {
                App? parent = await _db.App.FindByIdAsync(request.PId.Value);
                if (parent != null)
                {
                    if (parent.Level.IsNullOrEmpty())
                        model.Level = parent.Id + "";
                    else
                        model.Level = parent.Level + "," + parent.Id;
                }
            }
            if (request.Id == null)
                await _db.App.AddAsync(model);
            await _db.SaveChangesAsync();
        }
        /// <summary>
        /// 应用删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task Remove(long id)
        {
            var model = await _db.App.FindByIdAsync(id) ?? throw new ApiException("应用不存在!");
            var list = await _db.App.Where(x => x.Level != null && ("," + x.Level + ",").Contains("," + id + ",")).ToListAsync();
            if (list.Count > 0)
            {
                foreach (var l in list)
                {
                    l.IsEnable = false;
                }
            }
            model.IsEnable = false;
            await _db.SaveChangesAsync();
        }
    }
}
